<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
  useMessage,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  NTag,
  NSwitch,
  NFlex,
  NAvatar,
  NSelect,
  NImage,
  NDataTable, NAlert,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import { router } from '@/router'
import default_image from '@/assets/images/mz.jpg'
import { exportToExcel } from '@/utils/exportUtils'

defineOptions({ name: '退款审核' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '退款',
  initForm: {},
  doCreate: api.getOrders,
  doUpdate: api.createOrder,
  doDelete: api.deleteOrderRefund,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({
  attributeOption: [
    {
      id: 1,
      name: '描述模板',
    },
    {
      id: 2,
      name: '规格模板',
    },
  ],
  sevendayOption: [
    {
      id: 0,
      name: '待审核',
      label: '待审核',
      value: 0,
    },
    {
      id: 1,
      name: '已审核',
      label: '已审核',
      value: 1,
    },
  ],
  state_option: [],
  token: getToken(),
})


onMounted(() => {
  $table.value?.handleSearch()
})

const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = message.loading('正在准备导出数据...', { duration: 0 })

    // 获取表格数据
    const { data: tableData } = await api.getRefundList({
      ...queryItems.value,
      is_export:1
    })

    if (!tableData || tableData.length === 0) {
      message.warning('没有数据可以导出')
      return
    }

    // 处理数据格式
    const exportData = tableData.map(item => ({
      ID: item.id,
      单号: item.order_id,
      订单类型: item.type === 1 ? '储值金' : '现金',
      退款人: item.user_name,
      总金额: item.total_price,
      备注: item.remark,
      退款时间: item.created_at,
      审核状态: item.status === 1 ? '已通过' : '待审核'
    }))

    // 导出Excel
    exportToExcel(exportData, `退款审核记录_${formatDate(new Date())}`)
    message.success('导出成功')
    loading?.destroy()
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败: ' + error.message)
  } finally {
    loading?.destroy()
  }
}

const columns = [
  {
    title: '+',
    width: 60,
    key: 'select_tk_projects',
    align: 'center',
    type: 'expand',
    expandable: row => row.select_tk_projects !== null,
    renderExpand: (row) => {
      let goods = row.select_tk_projects ?? []
      let goods_columns = [
        {
          width: "auto",
          title: '项目名称',
          key: 'name',
        },
        {
          width: "auto",
          title: '退款单价',
          key: 'single_price'
        },
        {
          width: "auto",
          title: '数量',
          key: 'nums'
        }, {
          width: "auto",
          title: '总价',
          key: 'price',
          render(row) {
            return h('span', (row.single_price * row.nums).toFixed(2)) // 保留两位小数
          }
        }
      ]
      return h(NDataTable, {
        columns: goods_columns,
        striped: true,
        size: "small",
        data: goods,
        style: {width: '1000px', margin: '10px 60px','--n-td-padding': '10px 60px','--n-th-padding': '10px 60px'}
      })
    }
  },
    {
    title: 'ID',
    key: 'id',
    width: 60,
    align: 'center',
    ellipsis: {tooltip: true},
  },
  {
    title: '单号',
    key: 'order_id',
    width: 60,
    align: 'center',
    ellipsis: {tooltip: true},
  },
  {
    title: '订单类型',
    key: 'type',
    align: 'center',
    width: 50,
    ellipsis: {tooltip: true},
    render(row) {
      let tag = ['储值金','现金']
      if (row.type === 1) {
        tag = "储值金"
      }
      if (row.type === 2) {
        tag = "现金"
      }
      return h(
          NTag,
          {type: 'primary', size: 'small', bordered: false, style: {margin: '2px 3px'}},
          {default: () => tag}
      )
    },
  },
  {
    title: '退款人',
    key: 'user_name',
    width: 100,
    align: 'center',
    fixed: 'left',
    render(row) {
      return h(
          'div',
          {
            style: {whiteSpace: 'pre-line'}, // 允许换行
          },
          `${row.user_name}` // 使用换行符分隔
      );
    },
  },
  {
    title: '总金额',
    key: 'total_price',
    width: 60,
    align: 'center',
    ellipsis: {tooltip: true},
  },
    {
    title: '备注',
    key: 'remark',
    width: 150,
    align: 'center',
    ellipsis: {tooltip: true},
  },
  {
    title: '退款时间',
    key: 'created_at',
    width: '100',
    align: 'center',
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: row.states===1?'error':'primary',
              disabled: row.status === 1,
              style: 'margin-right: 8px;',
              onClick: () => {
                on_check(row,row.states===1?0:1)
              },
            },
            {
              default: () => row.status===1?'已通过':'待审核',
              icon: renderIcon(row.status===1?'material-symbols:check':'material-symbols:acute-outline', { size: 16 }),
            }
          ),
          []
        ),

        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                    style: 'margin-right: 0px;width:30px;',
                  },
                  {

                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除该记录吗?'),
          }
        ),
      ]
    },
  },
]

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

function on_check(row,states){
  api.checkOrderRefund({
    id:row.id,
    states:states
  }).then((res) => {
    $table.value?.handleSearch()
    message.success('更新成功');
  })
}

</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="退款审核列表">
    <template #action>
      <NButton type="info" @click="handleExport">
        <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />导出Excel
      </NButton>
    </template>
    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getRefundList"
        :scroll-x="1600"
    >
      <template #queryBar>
        <QueryBarItem label="客户姓名" :label-width="80">
          <NInput
              v-model:value="queryItems.user_name"
              clearable
              type="text"
              placeholder="请输入客户姓名"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
        <QueryBarItem label="退款时间" :label-width="70">
          <NDatePicker
              v-model:value="datetimeRange"
              type="datetimerange"
              clearable
              placeholder="请选择时间范围"
              @update:value="handleDateRangeChange"
          />
        </QueryBarItem>
        <QueryBarItem label="审核状态" :label-width="80">
          <NSelect
              v-model:value="queryItems.is_express"
              style="width: 150px"
              :options="data.sevendayOption"
              clearable
              placeholder="请选审核状态"
          />
        </QueryBarItem>
      </template>
    </CrudTable>
  </CommonPage>
</template>
